package com.mrduan.otgfilemanager.ui.getstrong;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import com.mrduan.otgfilemanager.App;
import com.mrduan.otgfilemanager.Config;
import com.mrduan.otgfilemanager.ui.main.MainActivity;
import com.mrduan.otgfilemanager.ui_sdcard.main.MainSdcardActivity;
import com.orhanobut.logger.Logger;
import com.shike.baselibrary.utils.SharepreferenceUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by duany on 2018/5/11.
 */

public class GetSdCard {

    private boolean find = false;

    private String searchPath = "";
    String key = "UdisConfig.cong";

    private Context context;
    public GetSdCard(Context context) {
        this.context = context;
    }

    public void startCheck() {

        getSdPath();
    }

    int time = 1;

    private void getSdPath() {
        if (find) {
            return;
        }
        redFile(context, SharepreferenceUtils.getString(context, "BASE_FILE_PATH", ""), "");

        if (find) {
            return;
        }
        List<String> paths = getAllExternalSdcardPath();
        for (String arg : paths) {
            if (find) {
                break;
            }
            redFile(context, arg, "");
        }
        paths = getExtSDCardPath();
        for (String arg : paths) {
            if (find) {
                break;
            }
            redFile(context, arg, "");
        }
        if (find) {
            return;
        }
        search(new File("/storage"));
        if (!searchPath.equals("")) {
            redFile(context, searchPath, "");
        }

        if (!find) {
            new Thread(){
                @Override
                public void run() {
                    try {
                        time ++;
                        sleep(1000);
                        if (time >= 5) {

                        } else {
                            ((GetStrongActivity)context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    getSdPath();
                                }
                            });
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }


    /**
     * 获取usb存储地址
     * @return
     */
    public static List<String> getAllExternalSdcardPath() {
        List<String> PathList = new ArrayList<String>();

        String firstPath = Environment.getExternalStorageDirectory().getPath();
        Logger.d("getAllExternalSdcardPath , firstPath = "+firstPath);

        try {
            // 运行mount命令，获取命令的输出，得到系统中挂载的所有目录
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            String line;
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                // 将常见的linux分区过滤掉
                if (line.contains("proc") || line.contains("tmpfs") || line.contains("media") || line.contains("asec") || line.contains("secure") || line.contains("system") || line.contains("cache")
                        || line.contains("sys") || line.contains("data") || line.contains("shell") || line.contains("root") || line.contains("acct") || line.contains("misc") || line.contains("obb")) {
                    continue;
                }

                // 下面这些分区是我们需要的
                if (line.contains("fat") || line.contains("fuse") || (line.contains("ntfs"))){
                    // 将mount命令获取的列表分割，items[0]为设备名，items[1]为挂载路径
                    String items[] = line.split(" ");
                    if (items != null && items.length > 1){
                        String path = items[1].toLowerCase(Locale.getDefault());
                        // 添加一些判断，确保是sd卡，如果是otg等挂载方式，可以具体分析并添加判断条件
                        if (path != null && !PathList.contains(path) && path.contains("sd"))
                            PathList.add(items[1]);
                    }
                }
            }
        } catch (Exception e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (!PathList.contains(firstPath)) {
            PathList.add(firstPath);
        }

        return PathList;
    }

    /**
     * 获取外置SD卡路径
     * @return  应该就一条记录或空
     */
    public List<String> getExtSDCardPath()
    {
        List<String> lResult = new ArrayList<String>();
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("extSdCard"))
                {
                    String [] arr = line.split(" ");
                    String path = arr[1];
                    File file = new File(path);
                    if (file.isDirectory())
                    {
                        lResult.add(path);
                    }
                }
            }
            isr.close();
        } catch (Exception e) {
        }
        return lResult;
    }


    /**
     * 获取到U盘的路径后读取文件
     * @param context
     * @param path
     * @param msg
     */
    private void redFile(final Context context, String path, String msg) {
        Logger.d(msg + " --" + path);
        if (find)
            return;

        Config.BASE_FILE_PATH = path;// /mnt/shell/emulated  // /storage/usbotg/usbotg-sda1
        if (!new File(Config.BASE_FILE_PATH + "/"+key).exists()) {
            if (!msg.equals(""))
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            return;
        }

        SharepreferenceUtils.saveString(context, "BASE_FILE_PATH", Config.BASE_FILE_PATH);

        boolean hasNewVersion = false;

        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();

            Config.oneScreenFiles.clear();
            Config.threeScreenFiles.clear();
            Config.twoScreenFiles.clear();
            for (File arg : files) {
                if (isNumeric(arg.getName())) {
                    int i = Integer.valueOf(arg.getName());
                    if (i <= 50) {
                        Config.oneScreenFiles.add(arg.getName());
                    } else if (i <= 100) {
                        Config.threeScreenFiles.add(arg.getName());
                    } else {
                        Config.twoScreenFiles.add(arg.getName());
                    }
                } else {
                    // 在这里检测版本更新
                    if (arg.getName().indexOf("apk") != -1) {
                        if (!arg.getName().equals(App.VERSION+".apk")) {
                            hasNewVersion = true;
                            installApk(arg);
                        }
                    }

                    if (arg.getName().equals("share")) {
                        File[] shares = arg.listFiles();
                        for (File share : shares) {
                            if (share.getName().equals(App.shareKey)) {
                                Config.shareFile = arg;
                            }
                        }

                    }

                }
            }
        }

        if (GetStrongActivity.hasSdCard) {
            return;
        }

        GetStrongActivity.hasSdCard = find = true;

        if (!hasNewVersion) {
            context.startActivity(new Intent(context, MainSdcardActivity.class));
            ((GetStrongActivity)context).finish();
        }
    }


    /**
     * 查找文件
     * @param fileold
     */
    private void search(File fileold) {
        try {
            File[] files = fileold.listFiles();

//            String a = fileold.getPath()+"\n";
            if (files != null && files.length > 0) {
                for (int j = 0; j < files.length; j++) {

//                    a += files[j].getPath() + "\n";

                    if (!files[j].isDirectory()) {
                        if (files[j].getName().indexOf(key) > -1) {
                            searchPath = files[j].getParent();
                        }
                    } else {
//                        Logger.d(files[j].getPath());
                        this.search(files[j]);
                    }
                }

//                Logger.i(a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    // 安装apk
    protected void installApk(File file) {

        try {
            Intent intent = new Intent();
            // 执行动作
            intent.setAction(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 执行的数据类型
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            context.startActivity(intent);
        } catch (Exception e) {
        }

    }
}
